package unrn.isiii.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.el.ELContext;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import unrn.isiii.model.Cliente;


@ManagedBean
@ViewScoped
public class ComplexMasterDetailController implements Serializable {

	private static final long serialVersionUID = 20111120L;

	private List<Cliente> clientes;

	public ComplexMasterDetailController() {
		if (clientes == null) {
			clientes = new ArrayList<Cliente>();
		}
	}

	public List<Cliente> getClientes() {
		return clientes;
	}

	public String saveSuccess(Cliente cliente) {
		FacesMessage message =
		    new FacesMessage(FacesMessage.SEVERITY_INFO, "Cliente " + cliente.getApellido() + " has been saved", null);
		FacesContext.getCurrentInstance().addMessage(null, message);

		return null;
	}

	public String saveFailure(Cliente cliente) {
		FacesContext fc = FacesContext.getCurrentInstance();
		ELContext elContext = fc.getELContext();

		SelectLevelListener selectLevelListener;
		try {
			selectLevelListener =
			    (SelectLevelListener) elContext.getELResolver().getValue(elContext, null, "selectLevelListener");
			selectLevelListener.setErrorOccured(true);
		} catch (RuntimeException e) {
			throw new FacesException(e.getMessage(), e);
		}

		FacesMessage message =
		    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Person " + cliente.getApellido() + " could not be saved", null);
		FacesContext.getCurrentInstance().addMessage(null, message);

		return null;
	}

	public String delete(Cliente cliente) {
		for (Cliente pers : clientes) {
			if (pers.getId().equals(cliente.getId())) {
				clientes.remove(pers);

				break;
			}
		}

		return null;
	}

	}


            
